import axios from 'axios'
import { User, AuthResponse, LoginCredentials, RegisterData, AuthTokens } from '@/types'
import { apiClient } from './apiClient'

class AuthService {
  async login(credentials: LoginCredentials): Promise<AuthResponse> {
    console.log('🔐 [DEBUG] authService.login() 开始');
    console.log('🔐 [DEBUG] 登录凭据:', { username: credentials.username, hasPassword: !!credentials.password });
    
    const response = await apiClient.post<any>('/auth/login', credentials)
    
    console.log('🔐 [DEBUG] 登录响应状态:', response.status);
    console.log('🔐 [DEBUG] 登录响应数据:', response.data);
    
    // 处理嵌套的响应格式 {success: true, data: {user, accessToken, refreshToken}}
    const authData = response.data.data || response.data;
    console.log('🔐 [DEBUG] 提取的认证数据:', authData);
    
    // 设置认证token (直接从data中获取accessToken)
    if (authData.accessToken) {
      console.log('✅ [DEBUG] 设置认证token:', authData.accessToken.substring(0, 20) + '...');
      this.setAuthToken(authData.accessToken)
    } else {
      console.log('⚠️ [DEBUG] 响应中没有accessToken');
      console.log('🔐 [DEBUG] authData结构:', Object.keys(authData));
    }
    
    // 返回符合AuthResponse格式的数据
    return {
      user: authData.user,
      tokens: {
        accessToken: authData.accessToken,
        refreshToken: authData.refreshToken
      }
    }
  }

  async register(data: RegisterData): Promise<AuthResponse> {
    const response = await apiClient.post<AuthResponse>('/auth/register', data)
    
    // 设置认证token
    if (response.data.tokens?.accessToken) {
      this.setAuthToken(response.data.tokens.accessToken)
    }
    
    return response.data
  }

  async refreshToken(refreshToken: string): Promise<AuthResponse> {
    const response = await apiClient.post<AuthResponse>('/auth/refresh', {
      refreshToken,
    })
    
    // 更新认证token
    if (response.data.tokens?.accessToken) {
      this.setAuthToken(response.data.tokens.accessToken)
    }
    
    return response.data
  }

  async verifyToken(token: string): Promise<User> {
    const response = await apiClient.get<{ user: User }>('/auth/verify', {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    
    return response.data.user
  }

  async logout(): Promise<void> {
    try {
      await apiClient.post('/auth/logout')
    } catch (error) {
      console.error('Logout API error:', error)
    } finally {
      this.clearAuthToken()
    }
  }

  async forgotPassword(email: string): Promise<void> {
    await apiClient.post('/auth/forgot-password', { email })
  }

  async resetPassword(token: string, password: string): Promise<void> {
    await apiClient.post('/auth/reset-password', { token, password })
  }

  async changePassword(currentPassword: string, newPassword: string): Promise<void> {
    await apiClient.post('/auth/change-password', {
      currentPassword,
      newPassword,
    })
  }

  // Token 管理方法
  setAuthToken(token: string): void {
    apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`
  }

  clearAuthToken(): void {
    delete apiClient.defaults.headers.common['Authorization']
  }

  getStoredToken(): string | null {
    try {
      const authData = localStorage.getItem('auth-storage')
      if (authData) {
        const parsed = JSON.parse(authData)
        return parsed.state?.tokens?.accessToken || null
      }
    } catch (error) {
      console.error('Error getting stored token:', error)
    }
    return null
  }

  // 初始化时设置token
  initializeToken(): void {
    const token = this.getStoredToken()
    if (token) {
      this.setAuthToken(token)
    }
  }
}

export const authService = new AuthService()

// 初始化时设置token
authService.initializeToken()